﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.IO.Ports;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;



namespace demo01
{
    public partial class Form1 : Form

    {

       int[,] pagematrix = new int[10000, 10000];
        public Form1()
        {
            InitializeComponent();
        }

        #region  postgres连接字符串
        //private static string connString = "Host=172.20.100.8;Port=5432;Username=postgres;Password=postgres;Database=kyekq";
        //NpgsqlConnection conn = new NpgsqlConnection(connString);
        #endregion
  
        #region 引入中控sdk,初始化
        // 引入dll ,嵌入互操作类型选择"否"
        public zkemkeeper.CZKEMClass axCZKEM1 = new zkemkeeper.CZKEMClass();
        //Create Standalone SDK class dynamicly.

        private bool bIsConnected = false;//the boolean value identifies whether the device is connected
        private int iMachineNumber = 1;//the serial number of the device.After connecting the device ,this value will be changed.

        public string userId = string.Empty;
        public string cardNumber = string.Empty;
        public string temp = string.Empty;
        public string qi = string.Empty;
        public string datetime = string.Empty;
        #endregion
        


        private void Form1_Load(object sender, EventArgs e)
        {

            //conn.Open();
            //MessageBox.Show("数据库打开成功!");

            string url = txt_Attend.Text;
            string url_temp = txt_Temp.Text;

            btnConnect_Click(sender, e);

        }

        #region 连接按钮
        private void btnConnect_Click(object sender, EventArgs e)
        {
            if (txtIP.Text.Trim() == "" || txtPort.Text.Trim() == "")
            {
                MessageBox.Show("IP and Port cannot be null", "Error");
                return;
            }
            //int idwErrorCode = 0;

            Cursor = Cursors.WaitCursor;
            if (btnConnect.Text == "DisConnect")
            {
                axCZKEM1.Disconnect();
                this.axCZKEM1.OnVerify -= new zkemkeeper._IZKEMEvents_OnVerifyEventHandler(axCZKEM1_OnVerify);
                this.axCZKEM1.OnAttTransactionEx -= new zkemkeeper._IZKEMEvents_OnAttTransactionExEventHandler(axCZKEM1_OnAttTransactionEx);
                this.axCZKEM1.OnHIDNum -= new zkemkeeper._IZKEMEvents_OnHIDNumEventHandler(axCZKEM1_OnHIDNum);

                bIsConnected = false;
                btnConnect.Text = "连接考勤机";
                Cursor = Cursors.Default;
                return;
            }

            bIsConnected = axCZKEM1.Connect_Net(txtIP.Text, Convert.ToInt32(txtPort.Text));
            if (bIsConnected == true)
            {
                
                btnConnect.Text = "DisConnect";
                btnConnect.Refresh();
                iMachineNumber = 1;//In fact,when you are using the tcp/ip communication,this parameter will be ignored,that is any integer will all right.Here we use 1.

                if (axCZKEM1.RegEvent(iMachineNumber, 65535))//Here you can register the realtime events that you want to be triggered(the parameters 65535 means registering all)
                {

                    this.axCZKEM1.OnVerify += new zkemkeeper._IZKEMEvents_OnVerifyEventHandler(axCZKEM1_OnVerify);
                    this.axCZKEM1.OnHIDNum += new zkemkeeper._IZKEMEvents_OnHIDNumEventHandler(axCZKEM1_OnHIDNum);
                    this.axCZKEM1.OnAttTransactionEx += new zkemkeeper._IZKEMEvents_OnAttTransactionExEventHandler(axCZKEM1_OnAttTransactionEx);

                }
            }
            else
            {
                //axCZKEM1.GetLastError(ref idwErrorCode);
                //MessageBox.Show("Unable to connect the device,ErrorCode=" + idwErrorCode.ToString(), "Error");
                MessageBox.Show("連接不到設備,檢查輸入或機器未連網");
            }
            Cursor = Cursors.Default;
        }


        //扫卡识别卡号
        private async void axCZKEM1_OnHIDNum(int iCardNumber)
        {
            Thread.Sleep(60);
            await Task.Run(() =>
            {
                cardNumber = iCardNumber.ToString();
                if (lbRTShow.Items.Count > 70)   // 大于70条记录清空
                {
                    lbRTShow.Items.Clear();
                }
               

                // 这里通过http提交表单到  url='http://172.20.100.28/api/v1/access/record'         


                var formDatas = new List<FormItemModel>();

                formDatas.Add(new FormItemModel()
                {
                    Key = "cardId",
                    Value = cardNumber
                });

                string result = PostForm(txt_Attend.Text, formDatas);
            });

            lbRTShow.Items.Add("-- cardId : " + iCardNumber.ToString());
            //Thread.Sleep(500);
            //lbRTShow.Items.Add("RTEvent OnHIDNum Has been Triggered...");
          
        }







        // 认证
         private async void axCZKEM1_OnAttTransactionEx(string sEnrollNumber, int iIsInValid, int iAttState, int iVerifyMethod, int iYear, int iMonth, int iDay, int iHour, int iMinute, int iSecond, int iWorkCode)
        {
            Thread.Sleep(50);
            await Task.Run(() => {
                userId = sEnrollNumber;
                datetime = iYear.ToString() + "-" + iMonth.ToString() + "-" + iDay.ToString() + " " + iHour.ToString() + ":" + iMinute.ToString() + ":" + iSecond.ToString();
            
            });
           

            lbRTShow.Items.Add("enrollNo: " + userId);
        }


        private void axCZKEM1_OnVerify(int iUserID)
        {
            
            if (iUserID != -1)
            {
                
                //userId = iUserID.ToString();
                //lbRTShow.Items.Add("userId: "+userId);
            }
            else
            {
                lbRTShow.Items.Add("Verified Failed... ");
            }
        }
        #endregion

        // 表单加载时尝试连接串口进行通迅
        // 接收串口送来的完整数据
        // 处理数据

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            //conn.Close();
        }

        //声明串口变量
        SerialPort serialPort1 = new SerialPort();




    
        // 串口传输温度数据处理
        private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {

            Thread.Sleep(50);

            try
            {
                int len = serialPort1.BytesToRead;
                string receivedata = string.Empty;
                
                if (len != 0)
                {
                    byte[] buff = new byte[len];
                    serialPort1.Read(buff, 0, len);
                    //接收到数据进行转换

                    receivedata = byteToHexStr(buff);
                    //receivedata = "06900524031FAC";

                    // 处理16进制数据形成体温  06900524031FAC
                    string temp_shi = Convert.ToInt32(receivedata.Substring(6, 2), 16).ToString();
                    string temp_xiao = Convert.ToInt32(receivedata.Substring(4, 2),16).ToString();
                    temp = temp_shi +"."+ temp_xiao;

                    // 处理16进制数据形成气温
                    string qi_shi = Convert.ToInt32(receivedata.Substring(10, 2), 16).ToString();
                    string qi_xiao = Convert.ToInt32(receivedata.Substring(8, 2), 16).ToString();
                    qi = qi_shi + "." + qi_xiao;


                }
                if (lbTemp.Items.Count>70)
                {
                    lbTemp.Items.Clear();
                }

                lbTemp.Items.Add("体温: " + temp+" ------ 气温: "+qi);
                var formDatas = new List<FormItemModel>();

                formDatas.Add(new FormItemModel()
                {
                    Key = "temperature",
                    Value = temp
                });

                string result = PostForm(txt_Temp.Text, formDatas);
                //textBox1.Text = result;

             


            }
            catch (Exception ex)
            {
                
                MessageBox.Show(ex.Message);
            }


        }
        //字节数组转16进制字符串
        public static string byteToHexStr(byte[] bytes)
        {
            string returnStr = "";
            if (bytes != null)
            {
                for (int i = 0; i < bytes.Length; i++)
                {
                    returnStr += bytes[i].ToString("X2");
                }
            }
            return returnStr;
        }



        private void btn_Temp_Click(object sender, EventArgs e)
        {
            try
            {
                 Cursor = Cursors.WaitCursor;
                 if (btn_Temp.Text == "DisConnect")
                    {
                        serialPort1.Close();
                        serialPort1.Dispose();
                        btn_Temp.Text = "连接体温计";
                        Cursor = Cursors.Default;
                    }
                 else
                    {
                         //波特率
                        serialPort1.BaudRate = 4800;
                        //数据位
                        serialPort1.DataBits = 8;
                        serialPort1.PortName = comboBox1.Text;
                        //两个停止位
                        serialPort1.StopBits = System.IO.Ports.StopBits.One;
                        //无奇偶校验位
                        serialPort1.Parity = System.IO.Ports.Parity.None;
                        serialPort1.ReadTimeout = 100;
                     ///
                        serialPort1.ReadBufferSize = 1024; //接收缓冲区大小
                        serialPort1.Encoding = Encoding.BigEndianUnicode;
                     ///
                        serialPort1.Open();
                        btn_Temp.Text = "DisConnect";
                        btnConnect.Refresh();
                        Cursor = Cursors.Default;
                    }
                    
                    serialPort1.DataReceived += serialPort1_DataReceived;
                   
            }

                
            catch (Exception)
            {
                
                //String[] portnames = SerialPort.GetPortNames();
                //foreach (var item in portnames)
                //{
                //    lbTemp.Items.Add(item);
                //}
                //MessageBox.Show(ex.Message);
                serialPort1.Dispose();
                serialPort1.Close();
                Cursor = Cursors.Default;
                
            }

                   
            }

        //定时监测考勤机,这里用不上
        private void rtTimer_Tick(object sender, EventArgs e)
        {
            if (axCZKEM1.ReadRTLog(iMachineNumber))
            {
                while (axCZKEM1.GetRTLog(iMachineNumber))
                {
                    ;
                }
            }

        }




        /// <summary>
        /// 使用Post方法获取字符串结果
        /// </summary>
        /// <param name="url"></param>
        /// <param name="formItems">Post表单内容</param>
        /// <param name="cookieContainer"></param>
        /// <param name="timeOut">默认20秒</param>
        /// <param name="encoding">响应内容的编码类型（默认utf-8）</param>
        /// <returns></returns>
        public static string PostForm(string url, List<FormItemModel> formItems, CookieContainer cookieContainer = null, string refererUrl = null, Encoding encoding = null, int timeOut = 20000)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            #region 初始化请求对象
            request.Method = "POST";
            request.Timeout = timeOut;
            request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
            request.KeepAlive = true;
            request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36";
            if (!string.IsNullOrEmpty(refererUrl))
                request.Referer = refererUrl;
            if (cookieContainer != null)
                request.CookieContainer = cookieContainer;
            #endregion

            string boundary = "----" + DateTime.Now.Ticks.ToString("x");//分隔符
            request.ContentType = string.Format("multipart/form-data; boundary={0}", boundary);
            //请求流
            var postStream = new MemoryStream();
            #region 处理Form表单请求内容
            //是否用Form上传文件
            var formUploadFile = formItems != null && formItems.Count > 0;
            if (formUploadFile)
            {
                //文件数据模板
                string fileFormdataTemplate =
                    "\r\n--" + boundary +
                    "\r\nContent-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"" +
                    "\r\nContent-Type: application/octet-stream" +
                    "\r\n\r\n";
                //文本数据模板
                string dataFormdataTemplate =
                    "\r\n--" + boundary +
                    "\r\nContent-Disposition: form-data; name=\"{0}\"" +
                    "\r\n\r\n{1}";
                foreach (var item in formItems)
                {
                    string formdata = null;

                    //上传文本
                    if (item.Value != null)
                    {
                        formdata = string.Format(
                        dataFormdataTemplate,
                        item.Key,
                        item.Value);
                    }
                    else
                    {
                        formdata = string.Format(
                        dataFormdataTemplate,
                        item.Key,
                        item.Values);
                    }
                    //统一处理
                    byte[] formdataBytes = null;
                    //第一行不需要换行
                    if (postStream.Length == 0)
                        formdataBytes = Encoding.UTF8.GetBytes(formdata.Substring(2, formdata.Length - 2));
                    else
                        formdataBytes = Encoding.UTF8.GetBytes(formdata);
                    postStream.Write(formdataBytes, 0, formdataBytes.Length);
                }
                //结尾
                var footer = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");
                postStream.Write(footer, 0, footer.Length);

            }
            else
            {
                request.ContentType = "application/x-www-form-urlencoded";
            }
            #endregion

            request.ContentLength = postStream.Length;

            #region 输入二进制流
            if (postStream != null)
            {
                postStream.Position = 0;
                //直接写入流
                Stream requestStream = request.GetRequestStream();

                byte[] buffer = new byte[1024];
                int bytesRead = 0;
                while ((bytesRead = postStream.Read(buffer, 0, buffer.Length)) != 0)
                {
                    requestStream.Write(buffer, 0, bytesRead);
                }

                ////debug
                //postStream.Seek(0, SeekOrigin.Begin);
                //StreamReader sr = new StreamReader(postStream);
                //var postStr = sr.ReadToEnd();
                postStream.Close();//关闭文件访问
            }
            #endregion

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            if (cookieContainer != null)
            {
                response.Cookies = cookieContainer.GetCookies(response.ResponseUri);
            }

            using (Stream responseStream = response.GetResponseStream())
            {
                using (StreamReader myStreamReader = new StreamReader(responseStream, encoding ?? Encoding.UTF8))
                {
                    string retString = myStreamReader.ReadToEnd();
                    return retString;
                }
            }
        }

           

        }
    }

